<template>
	<div>
		<div class="bg">
			<uni-nav-bar :fixed="true" title="信息登记" background-color="#5C7FF5" status-bar @clickLeft="back" :dark="true"
				left-icon="left">
			</uni-nav-bar>
			<view v-for="(item, index) in num" :key="index">
				<canvas :canvas-id="Canvas + index" :style="style"
					style="visibility: hidden; width: 0; height: 0"></canvas>
			</view>
			<div class="p50 bgwhite">

				<div class="contentItem">
					<div class="formLabel">
						*运维单位
					</div>
					<div class="formItem">
						<cus-selects v-model="form.org" :data='dwList' :clearable='true' :filterable='true' ref="org"
							@change="changeDw" :searchType='1' :refName="'org'"
							:valueType="{label:'name',value:'name'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						*所属电站
					</div>
					<div class="formItem">
						<cus-selects ref="station" :refName="'station'" v-model="form.station" :data="stationList"
							:clearable='true' :filterable='true' @change="changedz" :searchType='1'
							:valueType="{label:'station',value:'station'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						*电压等级
					</div>
					<div class="formItem">
						<cus-selects ref="voltage" :refName="'voltage'" v-model="form.voltage" :data="voltageList"
							:clearable='true' :filterable='true' @change="changedj" :searchType='1'
							:valueType="{label:'voltage',value:'voltage'}"></cus-selects>
					</div>
				</div>

			</div>
			<div class="line">
				缺陷登记
			</div>
			<div class="p50 bgwhite">
				<div class="contentItem">
					<div class="formLabel">
						*设备类型
					</div>
					<div class="formItem">
						<cus-selects ref="deviceType" :refName="'deviceType'" v-model="form.deviceType"
							:data="deviceTypeList" @change="changelx" :clearable='true' :filterable='true'
							:searchType='1' :valueType="{label:'deviceType',value:'deviceType'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						*设备名称
					</div>
					<div class="formItem">
						<cus-selects ref="deviceName" :refName="'deviceName'" v-model="form.deviceName"
							:data="deviceNameList" :clearable='true' :filterable='true' :searchType='1'
							:valueType="{label:'deviceName',value:'deviceName'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						部件类型
					</div>
					<div class="formItem">
						<cus-selects ref="partsType" :refName="'partsType'" v-model="form.partsType" :data="partyList"
							:clearable='true' :filterable='true' @change="changebj" :searchType='1'
							:valueType="{label:'partsType',value:'partsType'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						*缺陷描述
					</div>
					<div class="formItem">
						<cus-selects placeholder="请输入、搜索或者下拉选择" types="edit" ref="description"
							v-model="form.description" :data="descriList" :clearable='true' @change="changems"
							:filterable='true' :searchType='1' :valueType="{label:'description',value:'description'}"
							:refName="'description'"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						*缺陷性质
					</div>
					<div class="formItem">
						<cus-selects ref="level" v-model="form.level" :refName="'level'" :data="levelList"
							:clearable='true' :filterable='true' @change="changexz" :searchType='1'
							:valueType="{label:'level',value:'level'}"></cus-selects>
					</div>
				</div>
				<div class="contentItem">
					<div class="formLabel">
						分类依据
					</div>
					<div class="formItem">
						<!-- <div class="myTextArea"></div> -->
						<textarea placeholder="请输入分类依据" bindinput="onTextareaInput" v-model="form.classificationBasis"
							class="myTextArea" @change="toTextChange" style="font-size: 28rpx;" />
					</div>
				</div>
				<div class="contentItem" v-if="rules =='admin' || rules =='administrator'" style="margin-top: 8rpx;">
					<div class="formLabel">
						*缺陷发现人员
					</div>
					<div class="formItem">
						<input type="text" v-model.trim="form.name"
							style="border: 1rpx solid #707070;padding: 20rpx 20rpx;border-radius: 10rpx;font-size: 28rpx;"
							placeholder="请输入名称" @focus="toClear" maxlength="20">
					</div>
				</div>
			</div>
			<div class="p50 bgwhite" style="margin-top: 16rpx;">
				<uni-file-picker limit="9" multiple @success="success" @progress="progress" @fail="fail"
					@delete="deletes" @select="select" :del-icon="true" v-model="fileLists">
					<img src="../../static/img/isAdd.png" style="width: 72rpx;height: 60rpx;" alt="">
				</uni-file-picker>
			</div>
			<div class="addBtn">
				<div class="bts" @click="toRight">
					提交
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		findStation,
		findDictionary,
		findClassificationBasis,
		findDefectNature,
		findDescription,
		findDeviceName,
		findDeviceType,
		findPartType,
		saveAndUpdateDefect,
		findVoltage
	} from "@/utils/http"
	import {
		COM_URL,
		IMG_URL
	} from "@/utils/config";
	import cusSelects from '@/components/cus-selects-fan/cus-selects-fan.vue'
	import uniNavBar from '@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue'
	export default {
		onLoad(query) {

			this.comeForm = query.u
			this.getInt()

		},

		onShow() {
			this.rules = uni.getStorageSync('userInfo').role

		},

		components: {
			cusSelects,
			uniNavBar
		},

		data() {
			return {
				style: null,
				Canvas: "ll_canvas_img",
				type: null,
				num: 0,
				count: -1,
				titlesName: '',
				imgArr: [],
				form: {
					org: '',
					station: '',
					voltage: '',
					deviceType: '',
					deviceName: '',
					partsType: '',
					description: '',
					param: '',
					level: '',
					classificationBasis: '',
					path: [],
					name: '',
				},
				isUse: true,
				rules: '',

				ruleForm: [{
						name: 'org',
						text: '请选择运维单位'
					},
					{
						name: 'station',
						text: '请选择所属电站'
					},
					{
						name: 'voltage',
						text: '请选择电压等级'
					},
					{
						name: 'deviceType',
						text: '请选择设备类型'
					},
					{
						name: 'deviceName',
						text: '请选择设备名称'
					},
					// {name:'partsType',text:'请选择部件类型'},
					{
						name: 'description',
						text: '请选择缺陷描述'
					},
					{
						name: 'level',
						text: '请选择缺陷性质'
					},


				],
				fileLists: [],
				fileListsCopy: [],
				levelList: [],
				dwList: [], //单位
				stationList: [], //电站
				deviceTypeList: [], //设备类型
				deviceNameList: [], //设备名称
				voltageList: [], //电压
				descriList: [], //缺陷描述
				partyList: [], //部件类型
				comeForm: '',
			}
		},

		watch: {

		},

		methods: {
			success() {
				consoel.log(this.fileLists, 'success')
			},
			toClear() {
				this.$refs['org'].resetShow()

				this.$refs['station'].resetShow()
				this.$refs['voltage'].resetShow()
				this.$refs['deviceType'].resetShow()
				this.$refs['deviceName'].resetShow()
				this.$refs['partsType'].resetShow()
				this.$refs['description'].resetShow()
				this.$refs['level'].resetShow()
			},
			clearF(val) {
				this.$nextTick(() => {
					if (val == 'org') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'station') {
						this.$refs['org'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'voltage') {
						this.$refs['station'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'deviceType') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'deviceName') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'partsType') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'description') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['partsType'].resetShow()
						this.$refs['level'].resetShow()
					}
					if (val == 'level') {
						this.$refs['station'].resetShow()
						this.$refs['voltage'].resetShow()
						this.$refs['deviceType'].resetShow()
						this.$refs['deviceName'].resetShow()
						this.$refs['org'].resetShow()
						this.$refs['description'].resetShow()
						this.$refs['partsType'].resetShow()
					}
				})



			},
			deletes(val) {
				this.fileListsCopy.splice(val.index, 1)
				console.log(val.index, this.fileListsCopy.length, 'fileListsCopyL;ength')

			},
			// 提交
			toRight() {
				if (this.isUse) {
					this.isUse = false
					for (var i = 0; i < this.ruleForm.length; i++) {
						if (!this.form[this.ruleForm[i].name] && this.ruleForm[i].text) {
							this.isUse = true

							wx.showToast({
								title: this.ruleForm[i].text,
								icon: 'none'
							})
							return
						}
					}
					if (this.fileListsCopy.length == 0) {
						this.isUse = true

						wx.showToast({
							title: '请上传图片',
							icon: 'none'
						})
						return
					}
					if (this.rules == 'admin' || this.rules == 'administrator') {
						var regex = /[\u4e00-\u9fa5a-zA-Z0-9\p{P}]+$/u;

						if (!this.form.name) {

							wx.showToast({
								title: '请输入姓名',
								icon: 'none'
							})
							this.isUse = true

							return
						}
						if (!regex.test(this.form.name)) {
							wx.showToast({
								title: '请输入正确的姓名格式',
								icon: 'none'
							})
							this.isUse = true

							return
						}

					} else {
						this.form.name = uni.getStorageSync('userInfo').name


					}
					this.form.openid = uni.getStorageSync('openid')
					this.form.path = []
					for (var i = 0; i < this.fileListsCopy.length; i++) {
						if (this.fileListsCopy[i].path.indexOf(IMG_URL) >= 0) {
							this.form.path.push(this.fileListsCopy[i].path.split(IMG_URL)[1])

						} else {

							this.form.path.push(this.fileListsCopy[i].path)


						}
					}

					saveAndUpdateDefect(this.form).then(res => {
						if (res.code == '0') {
							uni.showToast({
								title: '操作成功',
								duration: 1500,
								mask: true
							})
							setTimeout(() => {
								if (uni.getStorageSync('isWarm')) {
									wx.removeStorageSync('isWarm');

									uni.switchTab({
										url: '/pages/order/jinggaoIndex'
									})
									uni.navigateBack({
										delta: 1 // 默认值是1，表示回退到上一页，如果要回退多级可以设置大于1的数值
									});

								} else {
									uni.navigateBack({
										delta: 1 // 默认值是1，表示回退到上一页，如果要回退多级可以设置大于1的数值
									});
									//                     if(this.comeForm == 'index'){
									//                   uni.reLaunch({
									//  url:'/pages/order/index'
									// })
									//                 }else if(this.comeForm =='admin'){
									//                   uni.reLaunch({
									//  url:'/pages/order/managerIndex'
									// })
									//                 }
								}
							}, 1300)


						}
					}).finally(() => {
						setTimeout(() => {
							this.isUse = true

						}, 2000)

					})
				}

			},

			//格式转换
			process_img(src, quality = 0.9, type = "jpg", ratio = 0.9) {
				return new Promise((resolve, reject) => {
					this.count++
					this.num++
					let Canvas = this.Canvas + this.count
					uni.getImageInfo({
						src: src,
						success: (res) => {
							let width = res.width
							let height = res.height
							this.style =
								`margin-top: -${height}px; margin-left: -${width}px; width: ${width}px; height: ${height}px;`
							setTimeout(() => {
								const ctx = uni.createCanvasContext(Canvas, this)
								ctx.clearRect(0, 0, width, height)
								ctx.drawImage(src, 0, 0, width, height)
								ctx.draw(false, () => {
									uni.canvasToTempFilePath({
											width: width,
											height: height,
											destWidth: width * ratio,
											destHeight: height * ratio,
											canvasId: Canvas,
											fileType: type,
											quality: quality,
											success: (res) => {


												console.log("格式转换成功")
												resolve(res.tempFilePath)
											},
											fail: (err) => {
												console.log("格式转换失败")
												reject(err)
											},
										},
										this
									)
								})
							}, 500)
						},
					})
				})
			},
			//图片压缩
			compress_img(src, size = 500, type = "jpg", ratio = 0.9) {
				return new Promise((resolve, reject) => {
					this.type = type
					this.process_img(src, 0.9, type).then((res) => {
						src = res
						this.compress(src, size, type)
							.then((res) => {
								console.log("压缩成功", res) // 输出压缩后的图片路径
								resolve(res)
							})
							.catch((err) => {
								reject(err)
							})
					})
				})
			},
			compress(src, size = 500, type, ratio = 0.9) {
				return new Promise((resolve, reject) => {
					uni.getFileInfo({
						filePath: src,
						success: (fileInfoRes) => {
							let fileSize = fileInfoRes.size / 1024 // 转换为KB
							if (fileSize > size) {
								// #ifndef H5
								this.process_img(src, 0.9, type, ratio)
									.then((res) => {
										src = res
										this.compress(src, size)
											.then((res) => {
												resolve(res)
											})
											.catch((err) => {
												reject(err)
											})
									})
									.catch((err) => {
										reject(err)
									})
								// #endif
								// #ifdef H5
								uni.getImageInfo({
									src: src,
									success: (res) => {
										let canvasWidth = res.width // 图片原始宽度
										let canvasHeight = res.height // 图片原始高度
										let img = new Image()
										img.src = res.path
										let canvas = document.createElement("canvas")
										let ctx = canvas.getContext("2d")
										// 这里根据要求限制图片宽高
										canvas.width = canvasWidth * ratio
										canvas.height = canvasHeight * ratio
										ctx.drawImage(img, 0, 0, canvas.width, canvas
											.height)
										//toBlob()方法创造Blob对象，用以展示canvas上的图片
										let type_h5
										if (this.type == "jpg") type_h5 = "image/jpeg"
										else if (this.type == "png") type_h5 = "image/png"
										else if (this.type == "webp") type_h5 =
											"image/webp"
										canvas.toBlob(
											(fileSrc) => {
												let imgSrc = window.URL
													.createObjectURL(fileSrc)
												this.compress(imgSrc, size).then((
													res) => {
													resolve(res)
												})
											},
											type_h5,
											0.9
										)
									},
								})
								// #endif
							} else {
								resolve(src)
							}
						},
					})
				})
			},
			// 上传图片
			async select(val) {
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				console.log(val, 'val')
				var that = this
				for (var i = 0; i < val.tempFilePaths.length; i++) {
					await this.doSomething(val.tempFilePaths[i]).then(res => {
						if (i == val.tempFilePaths.length - 1) {
							uni.hideLoading();
						}
					})

				}
				//     for (let i = 0; i < val.tempFilePaths.length; i++) {
				//     this.compress_img(
				//         val.tempFilePaths[i],
				//         1024,
				//         "jpg",
				//         0.8
				//       ).then(res=>{
				//         console.log(res)
				//         if(res){
				//           this.doSomething(res).then((res) => {

				// }).finally(()=>{
				//   uni.hideLoading();


				// })
				//         }

				//       })


				//     }
			},
			async doSomething(item) {
				var that = this;

				return new Promise((resolve, reject) => {

					uni.uploadFile({
						url: `${COM_URL}/manager/uploadPic`, //后端用于处理图片并返回图片地址的接口
						filePath: item,
						header: {
							token: uni.getStorageSync("token"),
						},
						name: "file",
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.code == '0') {
								that.fileListsCopy.push({
									url: `${IMG_URL}${data.result.path}`,
									path: data.result.path,
									ids: new Date().getTime().toString(),
									name: new Date().getTime().toString(),
									extname: "png",
								});
								resolve(item)

							} else {
								resolve(item)

							}
						},
						fail: () => {
							setTimeout(() => {
								uni.hideLoading();

							}, 1500)
						},
					});
				});


			},
			clearItem(arr) {
				arr.forEach(item => {
					this.$refs[item.ref].clearItem();
					this[item.list] = [];
					this.form[item.ref] = ''
				})

			},
			// 单位选择
			changeDw(val) {
				this.clearItem([{
					ref: 'station',
					list: 'stationList'
				}, {
					ref: 'voltage',
					list: 'voltageList'
				}, {
					ref: 'deviceType',
					list: 'deviceTypeList'
				}, {
					ref: 'deviceName',
					list: 'deviceNameList'
				}, {
					ref: 'partsType',
					list: 'partyList'
				}, {
					ref: 'description',
					list: 'descriList'
				}, {
					ref: 'level',
					list: 'levelList'
				}])
				if (val) {
					findStation({
						org: [val]
					}).then(res => {
						this.stationList = res.result
					})
				}

			},
			changedz(val) {
				this.clearItem([{
					ref: 'deviceType',
					list: 'deviceTypeList'
				}, {
					ref: 'deviceName',
					list: 'deviceNameList'
				}, {
					ref: 'partsType',
					list: 'partyList'
				}, {
					ref: 'description',
					list: 'descriList'
				}, {
					ref: 'level',
					list: 'levelList'
				}, {
					ref: 'voltage',
					list: 'voltageList'
				}, {
					ref: 'level',
					list: 'levelList'
				}, ])
				if (val) {
					findVoltage({
						station: val
					}).then(res => {
						this.voltageList = res.result
					})
				}

			},
			changedj(val) {
				this.clearItem([{
					ref: 'deviceName',
					list: 'deviceNameList'
				}, {
					ref: 'partsType',
					list: 'partyList'
				}, {
					ref: 'description',
					list: 'descriList'
				}, {
					ref: 'level',
					list: 'levelList'
				}, {
					ref: 'deviceType',
					list: 'deviceTypeList'
				}])
				if (val) {
					findDeviceType({
						voltage: val,
						station: this.form.station
					}).then(res => {
						this.deviceTypeList = res.result


					})
				}

			},
			changelx(val) {
				this.clearItem([{
					ref: 'deviceName',
					list: 'deviceNameList'
				}, {
					ref: 'partsType',
					list: 'partyList'
				}, {
					ref: 'description',
					list: 'descriList'
				}, {
					ref: 'level',
					list: 'levelList'
				}])
				if (val) {
					findDeviceName({
						voltage: this.form.voltage,
						station: this.form.station,
						deviceType: val
					}).then(res => {
						this.deviceNameList = res.result
					})
					findPartType({
						deviceType: val
					}).then(res => {
						this.partyList = res.result
					})
					findDescription({
						deviceType: val,
						partsType: this.form.partsType
					}).then(res => {
						this.descriList = res.result

					})
				}

			},


			changebj(val) {
				this.$nextTick(() => {
					this.clearItem([{
						ref: 'description',
						list: 'descriList'
					}, {
						ref: 'level',
						list: 'levelList'
					}])


					findDescription({
						partsType: val,
						deviceType: this.form.deviceType
					}).then(res => {
						this.descriList = res.result
					})
					findDefectNature({
						description: this.form.description,
						partsType: val,
						deviceType: this.form.deviceType
					}).then(res => {
						this.levelList = res.result
					})

				})

			},

			changems(val) {
				this.clearItem([{
					ref: 'level',
					list: 'levelList'
				}])
				// console.log(val, 'rrrrrr')
				// // findDescription({
				// // 	param: val,
				// // 	// partsType: val,
				// // 	// deviceType: this.form.deviceType
				// // }).then(res => {
				// // 	// console.log(res, 'rrrrrr')
				// // 	// this.descriList = res.result
				// // })
				if (val) {
					findDefectNature({
						description: val,
						partsType: this.form.partsType,
						deviceType: this.form.deviceType
					}).then(res => {
						this.levelList = res.result
					})
				}
			},
			changexz(val) {
				if (this.form.description && this.form.deviceType && this.form.level) {
					findClassificationBasis({
						description: this.form.description,
						partsType: this.form.partsType,
						deviceType: this.form.deviceType,
						level: val
					}).then(res => {

						this.form.classificationBasis = '';

						if (res.result.length > 0) {
							res.result.forEach(item => {
								this.form.classificationBasis += item.classificationBasis + ' '
							})
							this.form.classificationBasis = this.form.classificationBasis.slice(0, -1)
						}

					})
				} else {
					this.form.classificationBasis = ''

				}


			},



			// 
			getInt() {

				// 获取电站
				findDictionary({
					code: 'ORG'
				}).then(res => {
					this.dwList = res.result
					if (uni.getStorageSync('userInfo').role != "admin") {
						this.form.org = res.result[0].name
						findStation({
							org: [this.form.org]
						}).then(res => {
							this.stationList = res.result
						})
					}

				})
			},
			back() {
				uni.navigateBack({
					delta: 1 // 默认值是1，表示回退到上一页，如果要回退多级可以设置大于1的数值
				});
			},

		}
	};
</script>

<style scoped lang="scss">
	.bg {
		box-sizing: border-box;
		// padding:0rpx 50rpx;
		height: 100vh;
		background: #F5F6F8;

		.formLabel {
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: 400;
			font-size: 28rpx;
			color: #262626;
			margin-bottom: 20rpx;
		}

		.p50 {
			padding: 20rpx 50rpx;

		}

		.bgwhite {
			background: white;
			box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0, 0, 0, 0.16);
		}

		.formItem {}

		.line {
			box-sizing: border-box;
			padding: 0rpx 50rpx;
			margin: 16rpx 0;
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: bold;
			font-size: 30rpx;
			color: #313131;
		}

		.myTextArea {
			width: 650rpx;
			height: 200rpx;
			box-sizing: border-box;
			padding: 24rpx 20rpx;
			min-height: 168rpx;
			background: #FFFFFF;
			border-radius: 6rpx 6rpx 6rpx 6rpx;
			border: 2rpx solid #707070;
		}
	}

	.addBtn {
		padding-bottom: 30rpx;
		line-height: 80rpx;

		.bts {
			text-align: center;
			width: 650rpx;
			height: 80rpx;

			background: #5C7FF5;
			box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0, 0, 0, 0.16);
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: 500;
			font-size: 36rpx;
			color: #FFFFFF;
			margin: 30rpx auto;
		}
	}
</style>
<style scoped>
	.bg>>>.uni-nav-bar-text {
		font-size: 35rpx;
	}

	.bg>>>.icon-del-box {
		width: 40rpx;
		height: 40rpx;
		background-color: red;

	}

	.bg>>>.icon-del {
		width: 20rpx;
		height: 4rpx;
	}
</style>